package org.jeecg.modules.inOrder.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.Inventory.entity.Inventory;
import org.jeecg.modules.Inventory.service.IInventoryService;
import org.jeecg.modules.basicSku.entity.BasicSku;
import org.jeecg.modules.basicSku.service.IBasicSkuService;
import org.jeecg.modules.inOrder.entity.InOrder;
import org.jeecg.modules.inOrder.entity.InOrderZi;
import org.jeecg.modules.inOrder.service.IInOrderService;
import org.jeecg.modules.inOrder.service.IInOrderZiService;
import org.jeecg.modules.inOrder.vo.InOrderPage;
import org.jeecg.modules.operationLog.entity.OperationLog;
import org.jeecg.modules.operationLog.service.IOperationLogService;
import org.jeecg.modules.outOrder.service.IOutOrderService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 入库单主表
 * @Author: jeecg-boot
 * @Date: 2024-06-26
 * @Version: V1.0
 */
@Api(tags = "入库单主表")
@RestController
@RequestMapping("/inOrder/inOrder")
@Slf4j
public class InOrderController {
    @Autowired
    private IInOrderService inOrderService;
    @Autowired
    private IInOrderZiService inOrderZiService;
    @Autowired
    private IBasicSkuService basicSkuService;
    @Autowired
    private IInventoryService inventoryService;
    @Autowired
    private IOperationLogService operationLogService;
    @Autowired
    private IOutOrderService outOrderService;

    /**
     * 分页列表查询
     *
     * @param inOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "入库单主表-分页列表查询")
    @ApiOperation(value = "入库单主表-分页列表查询", notes = "入库单主表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(InOrder inOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<InOrder> queryWrapper = QueryGenerator.initQueryWrapper(inOrder, req.getParameterMap());
        if ((inOrder.getNum() != null && !inOrder.getNum().isEmpty()) || (inOrder.getSkucode() != null && !inOrder.getSkucode().isEmpty()) || (inOrder.getSkuname() != null && !inOrder.getSkuname().isEmpty()) || (inOrder.getCustomername() != null && !inOrder.getCustomername().isEmpty())) {
            LambdaQueryWrapper<InOrderZi> wrapper = new LambdaQueryWrapper<>();
            if ((inOrder.getSkucode() != null && !inOrder.getSkucode().isEmpty())) {
                wrapper.eq(InOrderZi::getSkuCode, inOrder.getSkucode());
            }
            if ((inOrder.getNum() != null && !inOrder.getNum().isEmpty())) {
                wrapper.eq(InOrderZi::getNumber, inOrder.getNum());
            }
            if ((inOrder.getSkuname() != null && !inOrder.getSkuname().isEmpty())) {
                wrapper.eq(InOrderZi::getSkuName, inOrder.getSkuname());
            }
            if ((inOrder.getCustomername() != null && !inOrder.getCustomername().isEmpty())) {
                wrapper.eq(InOrderZi::getCustomerName, inOrder.getCustomername());
            }
            List<String> ids = inOrderZiService.list(wrapper).stream().map(InOrderZi::getInOrderId).collect(Collectors.toList());
            if (ids.isEmpty()) {
                return Result.OK(new Page<InOrder>());
            } else {
                queryWrapper.in("id", ids);
            }
        }
        Page<InOrder> page = new Page<InOrder>(pageNo, pageSize);
        IPage<InOrder> pageList = inOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "市贩品-入库")
    @ApiOperation(value = "市贩品-入库", notes = "市贩品-入库")
    @PostMapping("/confirm")
    public Result<?> confirm(@RequestBody InOrder inOrder) {
        InOrder byId = inOrderService.getById(inOrder.getId());
        if (byId == null) {
            return Result.error("未找到对应数据");
        }
        if (byId.getStatus() == 1) {
            return Result.error("此入库单已入库,请勿重复操作");
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<InOrderZi> inOrderZis = inOrderZiService.selectByMainId(byId.getId());
        List<Inventory> addList = new ArrayList<>();
        List<OperationLog> operationLogs = new ArrayList<>();
        for (InOrderZi inOrderZi : inOrderZis) {
            inOrderZi.setInTime(inOrderZi.getInTime() == null ? byId.getInTime() : inOrderZi.getInTime());
            inOrderZi.setInventory(inOrderZi.getNumber());
            inOrderZi.setStatus(0);
            String skuCode = inOrderZi.getSkuCode();
            String location = inOrderZi.getLocation();
            OperationLog operationLog = new OperationLog();
            Inventory inventory = new Inventory();
            BeanUtils.copyProperties(inOrderZi, inventory);
            inventory.setId(null).setCreateBy(null).setCreateTime(null).setUpdateBy(null).setUpdateTime(null);
            addList.add(inventory);
            operationLog.setNewNumber(inOrderZi.getNumber());
            operationLog.setSkuCode(skuCode).setSkuName(inOrderZi.getSkuName()).setNumber(inOrderZi.getNumber())
                    .setOperationTime(new Date()).setOperationType("入库").setOperator(user.getRealname())
                    .setLocation(location).setInTime(inOrderZi.getInTime());
            operationLogs.add(operationLog);
        }
        inventoryService.saveBatch(addList);
        byId.setStatus(1);
        byId.setRealname(user.getRealname());
        inOrderService.updateById(byId);
        inOrderZiService.updateBatchById(inOrderZis);
        operationLogService.saveBatch(operationLogs);
        return Result.OK("入库成功", null);
    }

    /**
     * 添加
     *
     * @param inOrderPage
     * @return
     */
    @AutoLog(value = "入库单主表-添加")
    @ApiOperation(value = "入库单主表-添加", notes = "入库单主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody InOrderPage inOrderPage) {
        List<BasicSku> skus = basicSkuService.list();
        Map<String, BasicSku> collect = skus.stream()
                .collect(Collectors.toMap(
                        BasicSku::getSkuCode, // 键为 skuCode
                        Function.identity() // 值为 BasicSku 实例自身
                ));
        Result<Object> error = getResult(inOrderPage.getInOrderZiList(), collect);
        if (error != null) return error;
        InOrder inOrder = new InOrder();
        BeanUtils.copyProperties(inOrderPage, inOrder);
        inOrderService.saveMain(inOrder, inOrderPage.getInOrderZiList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param inOrderPage
     * @return
     */
    @AutoLog(value = "入库单主表-编辑")
    @ApiOperation(value = "入库单主表-编辑", notes = "入库单主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody InOrderPage inOrderPage) {
        InOrder inOrder = new InOrder();
        BeanUtils.copyProperties(inOrderPage, inOrder);
        InOrder inOrderEntity = inOrderService.getById(inOrder.getId());
        if (inOrderEntity == null) {
            return Result.error("未找到对应数据");
        }
        inOrderService.updateMain(inOrder, inOrderPage.getInOrderZiList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表-通过id删除")
    @ApiOperation(value = "入库单主表-通过id删除", notes = "入库单主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        inOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "入库单主表-批量删除")
    @ApiOperation(value = "入库单主表-批量删除", notes = "入库单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.inOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表-通过id查询")
    @ApiOperation(value = "入库单主表-通过id查询", notes = "入库单主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        InOrder inOrder = inOrderService.getById(id);
        if (inOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(inOrder);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单子表通过主表ID查询")
    @ApiOperation(value = "入库单子表主表ID查询", notes = "入库单子表-通主表ID查询")
    @GetMapping(value = "/queryInOrderZiByMainId")
    public Result<?> queryInOrderZiListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<InOrderZi> inOrderZiList = inOrderZiService.selectByMainId(id);
        return Result.OK(inOrderZiList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param inOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InOrder inOrder) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<InOrder> queryWrapper = QueryGenerator.initQueryWrapper(inOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<InOrder> queryList = inOrderService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<InOrder> inOrderList = new ArrayList<InOrder>();
        if (oConvertUtils.isEmpty(selections)) {
            inOrderList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            inOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<InOrderPage> pageList = new ArrayList<InOrderPage>();
        for (InOrder main : inOrderList) {
            InOrderPage vo = new InOrderPage();
            BeanUtils.copyProperties(main, vo);
            List<InOrderZi> inOrderZiList = inOrderZiService.selectByMainId(main.getId());
            vo.setInOrderZiList(inOrderZiList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "入库单主表列表");
        mv.addObject(NormalExcelConstants.CLASS, InOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库单主表数据", "导出人:" + sysUser.getRealname(), "入库单主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<InOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), InOrderPage.class, params);
                List<BasicSku> skus = basicSkuService.list();
                Map<String, BasicSku> collect = skus.stream()
                        .collect(Collectors.toMap(
                                BasicSku::getSkuCode, // 键为 skuCode
                                Function.identity() // 值为 BasicSku 实例自身
                        ));
                for (InOrderPage page : list) {
                    List<InOrderZi> inOrderZis = page.getInOrderZiList();
                    List<InOrderZi> inOrderZiList = inOrderZis.stream()
                            .filter(inOrderZi -> inOrderZi.getSkuCode() != null).collect(Collectors.toList());
                    Result<Object> error = getResult(inOrderZiList, collect);
                    if (error != null) return error;
                    InOrder po = new InOrder();
                    BeanUtils.copyProperties(page, po);
                    po.setInTime(po.getInTime() == null ? new Date() : po.getInTime());
                    inOrderService.saveMain(po, inOrderZiList);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    private static @Nullable Result<Object> getResult(List<InOrderZi> inOrderZiList, Map<String, BasicSku> collect) {
        for (InOrderZi inOrderZi : inOrderZiList) {
            String sku = inOrderZi.getSkuCode().replaceAll(" ", "");
            String location = inOrderZi.getLocation().replaceAll(" ", "");
            inOrderZi.setSkuCode(sku);
            inOrderZi.setLocation(location);
            if (collect.containsKey(sku)) {
                BasicSku basicSku = collect.get(sku);
                inOrderZi.setCustomerCode(basicSku.getCustomerCode()).setCustomerName(basicSku.getCustomerName())
                        .setSkuName(basicSku.getSkuName()).setBrand(basicSku.getBrand())
                        .setLength(basicSku.getLength()).setWidth(basicSku.getWidth())
                        .setHeight(basicSku.getHeight()).setWeight(basicSku.getWeight());
            } else {
                return Result.error("入库单中【" + inOrderZi.getSkuCode() + "】品番不存在,若确认无误，请先维护品番数据");
            }
        }
        return null;
    }

}
